<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;
use app\common\model\Crawls;
use app\common\model\CrawlEmails;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use app\common\library\Ai;
use app\common\library\Crawl as AiCrawl;
/**
 * 抓取網絡email
 */
class Crawl extends Api
{
    protected $noNeedRight = '*';
    protected $noNeedLogin = ['emails'];
    public function _initialize()
    {
        parent::_initialize();

    }
    /**抓取 */
    public function store(){
        $url = $this->request->post('url');
        if(!isset($url) || empty($url)){
            $this->error(__('Enter a full domain (http://example.com)1'));
        }   
        $result = filter_var($url, FILTER_VALIDATE_URL);
        if($result == false){
            $this->error(__('Enter a full domain (http://example.com)2'));
        }
        $depth = $this->request->post('depth',2);
        $data['url'] = $url;
        $data['user_id'] = $this->auth->id;
        Db::startTrans();
        try {
            $emails = Ai::instance()->getEmails($url);
            if(empty($emails)){
                throw new Exception("Capture 0 email");
            }
            $model = new Crawls;
            $email_count = count($emails);
            $data['email_count'] = $email_count;
            $data['pages'] = 1;
            $data['author'] = $this->auth->nickname;
            $crawl_id = $model->allowField(true)->save($data);
            $items = [];
            foreach($emails as $email){
                //$email = $this->generateRandomEmail();
                $items[] = [
                    'user_id'  => $this->auth->id,
                    'crawl_id' => $model->id,
                    'email'    => $email,
                    'author'   => $this->auth->nickname,
                    'created_at' => time()
                ];
            }
            (new CrawlEmails)->insertAll($items);
            Db::commit();
        }catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success(__('capture successful'),['crawl_id' => $model->id,'count' => $email_count]);
    }   
    /**
     * 歷史記錄
     */
    public function history($page = null){
        $map = ['user_id' => $this->auth->id];
        $items = Crawls::where($map)->order('id desc')->paginate(10);
        foreach($items as $item){
            $item->created_at = date('M d Y, H:i A',$item->created_at);
        }
        $this->success(__('capture successful'),$items);
    }  
    /**
     * 刪除
     */
    public function delete($id=null){
        $map = ['user_id' => $this->auth->id,'id' => intval($id)];
        $row = Crawls::where($map)->find();
        if(empty($row)){
            $this->error(__('not found'));
        }
        $row->delete();
        $this->success(__('successful'));
    } 

    public function emails($url=null,$depth = 2){
        $res = AiCrawl::instance()->crawlEmails($url,$depth);
        return json_encode(['answer' => $res],JSON_UNESCAPED_UNICODE);
        //$this->success(__('successful'),$res);
    }
}